<?php

namespace Apps\AppApi\Method\Common;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Models\QuestionTag;

/**
 * 获取问答热门标签
 * @author      545
 * @date        2016年1月11日
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */
class HotTag extends BaseMethod
{
    public function run()
    {
        $limit = $this->getConfig()->limit;
        //统计问答标签出现的次数 倒序获取次数最多即热门标签
        $list = QuestionTag::query()
            ->columns('b.tag_id id,tag_name name')
            ->join('Apps\Common\Models\BeautyParlorTagInfo','Apps\Common\Models\QuestionTag.tag_id = b.tag_id','b')
            ->where('tag_state = 1 AND b.parent_id IN (SELECT s.tag_id FROM Apps\Common\Models\BeautyParlorTagInfo as s WHERE tag_state>0 AND parent_id=0 ) GROUP BY Apps\Common\Models\QuestionTag.tag_id')
            ->orderBy('COUNT(Apps\Common\Models\QuestionTag.tag_id) desc')
            ->limit($limit,0)
            ->execute()->toArray();
        //如果热门标签不足 获取 最新标签补足
        if (count($list)<$limit){
            $limit -=count($list);
            $temp = BeautyParlorTagInfo::query()
            ->columns(['tag_id id', 'tag_title name'])
            ->where('tag_state = 1 AND  parent_id IN (SELECT tag_id FROM Apps\Common\Models\BeautyParlorTagInfo WHERE tag_state>0 AND parent_id=0 )')
            ->orderBy('tag_id DESC')
            ->limit($limit,0)
            ->execute()
            ->toArray();
            //合并数据
            $list = array_merge($list,$temp);
        }
        $this->setResult($list);
    }
}